import React from 'react'
import { Editor as MonacoEditor } from '@monaco-editor/react'
import type { OnMount ,EditorProps} from '@monaco-editor/react'
import { createATA } from './ata'
import { editor } from 'monaco-editor'
interface EditorFile {
    name: string,
    language: string,
    value: string,
}
interface Props {
    file: EditorFile,
    onChange: EditorProps['onChange'],
    options?: editor.IStandaloneEditorConstructionOptions
}
export default function Editor(props: Props) {
    const { file, onChange, options } = props
    const handleEditorMount: OnMount = (editor, monaco) => {
        monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
            jsx: monaco.languages.typescript.JsxEmit.Preserve,
            esModuleInterop: true,
            moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
            target: monaco.languages.typescript.ScriptTarget.Latest,
            allowNonTsExtensions: true,
            allowJs: true,
        })
        const ata = createATA((code, path) => {
            monaco.languages.typescript.typescriptDefaults.addExtraLib(code, `file://${path}`);
        })
        editor.onDidChangeModelContent(() => {
            ata(editor.getValue());
        })
    }

    return (
        <MonacoEditor
            path={file.name}
            height="100%"
            language={file.language}
            value={file.value}
            onMount={handleEditorMount}//编辑器挂载时触发
            onChange={onChange}
            options={
                {
                    fontSize: 14,
                    scrollBeyondLastLine: false,
                    minimap: {
                        enabled: false,
                    },
                    scrollbar: {
                        verticalScrollbarSize: 6,
                        horizontalScrollbarSize: 6,
                    },
                    ...options,
                }
            }
        />
    )
}
